package cn.com.woxitech.dev.controller.api;

import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;

import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.CodeUtils;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.PrivilegeService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.SettingService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@RestController
@RequestMapping("/luyan")
public class PPTLUYANController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	SettingService settingService;
	@Autowired
	PrivilegeService privilegeService;
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;
	@Autowired
	AppService appService;
	@Autowired
	private Environment env;
	

    @Autowired
    public SimpMessagingTemplate simp;

	

	@RequestMapping(value = "/ppt/server", method = RequestMethod.POST)
	public Object ppt_verify(@RequestBody String body) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			
			mp.put("pptserver", env.getProperty("pptserver"));
			mp.put("callbackurl", env.getProperty("pptcallbackurl"));
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}
    
	@RequestMapping(value = "/ppt/verify/code/{code}", method = RequestMethod.POST)
	public Object ppt_verify(@PathVariable String code, @RequestBody String body) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			String userid = roomService.verifyPPTAuthCode(code);
			
			if(userid == null){
				return APIResultFactory.fail();
			}
			WmUser user = this.userService.getUserByUuid(userid);
			mp.put("userid", userid);
			mp.put("headimgurl", user.getWxHeadimgurl());
			mp.put("name", user.getName());
			mp.put("type", userid);
			mp.put("pptserver", env.getProperty("pptserver"));
			mp.put("callbackurl", env.getProperty("pptcallbackurl"));
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}
	@RequestMapping(value = "/ppt/auth/userid/{_userid}", method = RequestMethod.POST)
	public Object ppt_auth(@PathVariable String _userid, @RequestBody String body) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			
			String code = CodeUtils.generateSMSVerifyCode(3);
			roomService.savePPTAuthCode(code, _userid);
			
			return APIResultFactory.success(code);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail();
		}
	}

	
	@RequestMapping(value = "/pptcallback/userid/{_userid}/pptkey/{pptkey}", method = RequestMethod.POST)
	public void pptcallback(@PathVariable String _userid, @PathVariable String pptkey, @RequestBody String body) {

		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			
			JsonNode bodyNode = JSONUtils.toJson(body);
			String pptname = bodyNode.get("pptname").asText();
			pptname = URLDecoder.decode(pptname,"utf-8");
			String url = env.getProperty("pptserver") + "/ppt_to_jpg/" + pptkey + "/status";
			String res = HttpClientUtils.sendGET(url);

			JsonNode jsonNode = JSONUtils.toJson(res);
			WmUser user = this.userService.getUserByUuid(_userid);
			if (user == null) {
				return;
			}
			String useruuid = user.getUuid();

			// {"status":true,"content":{"count":24,"pages":["ppt-0.jpg","ppt-1.jpg","ppt-2.jpg","ppt-3.jpg","ppt-4.jpg","ppt-5.jpg","ppt-6.jpg","ppt-7.jpg","ppt-8.jpg","ppt-9.jpg","ppt-10.jpg","ppt-11.jpg","ppt-12.jpg","ppt-13.jpg","ppt-14.jpg","ppt-15.jpg","ppt-16.jpg","ppt-17.jpg","ppt-18.jpg","ppt-19.jpg","ppt-20.jpg","ppt-21.jpg","ppt-22.jpg","ppt-23.jpg"]}}
			if(!jsonNode.get("status").asBoolean()){
				return;
			}
			int count = jsonNode.get("content").get("count").asInt();
			
			String ppturlbase = "/attachment/ppt/" + pptkey + "_dir/";
			String roomuuid = UUID.randomUUID().toString();
			String roomname = pptname;
			Date now = new Date(System.currentTimeMillis());
			Date starttime = now;
			String live_type = "2";
			String room_type = "1";
			String coverurl = ppturlbase + "ppt-0.jpg";
			String des = "";

			WmRoom room = new WmRoom();
			room.setThumburl(user.getWxHeadimgurl());
			room.setRoomchairs(user.getName());
			room.setCoverurl(coverurl);
			room.setLivecoverurl(coverurl);
			room.setName(roomname);
			room.setCreatetime(new Date(System.currentTimeMillis()));
			room.setTime(starttime);
			room.setCreatoruuid(useruuid);
			room.setLiveType(live_type);
			room.setRoomType(room_type);
			room.setDes(des);
			room.setUuid(roomuuid);
			room.setEndtime(new Date(System.currentTimeMillis() + 1000 * 60 * 90));

			this.roomService.insertRoom(room);

			WmLecture lecture = new WmLecture();
			lecture.setCreatorid(useruuid);
			lecture.setRoomid(room.getUuid());
			lecture.setName(room.getName());
			lecture.setUuid(UUID.randomUUID().toString());
			this.lectureService.insertLecture(lecture);
			
			for(int i = 0 ;i < count; i++){
				
				WmLecturePage page = new WmLecturePage();
				page.setCreatorid(useruuid);
				page.setLectureid(lecture.getUuid());
				page.setNum(i+1);
				page.setPageurl(ppturlbase+"ppt-"+i+".jpg");
				page.setType("img");
				page.setTime(now);
				this.lecturePageService.insertLecturePage(page);
			}
			
			
			//插入smalllive
			Map<String, Object> stream_map = qiniuService.createQiniuStream();
			String rtmpstreamserver = (String)stream_map.get("publishurl");
			String key = (String)stream_map.get("streamid");
			String hlsstreamserver = (String)stream_map.get("playurl");
			WmLecturePage page = new WmLecturePage();
			page.setCreatorid(room.getCreatoruuid());
			page.setLectureid(lecture.getUuid());
			page.setNum(999);
			page.setPageurl(hlsstreamserver);
			page.setPublishid(key);
			page.setThumburl(ppturlbase+"ppt-0.jpg");
			page.setPublishurl(rtmpstreamserver);
			page.setTime(new Date(System.currentTimeMillis()));
			page.setType("smalllive");
			this.lecturePageService.insertLecturePage(page);
			//end
			
			String publiccataloguuid = "ce6a8705-7e41-4983-b2fc-d04c33edc83c";
			this.catalogService.insertCatalog_Room(publiccataloguuid, room.getUuid());

//			SMSCodeUtils.sendPPTDoneNotify(user.getTel(), pptname, ""+count);
//			Map<String, Object> reqBody = new HashMap<String,Object>();
//			reqBody.put("type", "uploaded");
//			simp.convertAndSend("/ws/private/ppt/key/"+useruuid, body);
//			System.out.println("SendTo: /ws/private/ppt/key/"+useruuid);
			
			
			return;

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
